/****************************************************************
 ** Product  :   HP Subscriber Network Application Policy
 ** Module   :   gr-manager
 ** Date: Apr 10, 2015               
 ** Author: Chen Zhenhua
 ** (C) Copyright 2015, Hewlett-Packard Company, All Rights Reserved.
 ** This software is the proprietary information of HP, Inc.  
 ** Use is subject to license terms.
 *****************************************************************
 ** Description:   
 **    execute local shell script
 **    
 ****************************************************************/
package com.hp.snap.gr.action.impl;

/**
 * 
 * 
 * Execute local shell script, The stdout and stderr from result will be saved in action output respectively.
 * 
 * There are some parameter can be configured in the action: Shell, isFile and fileMode.
 * 
 * Shell: local shell script.
 * isFile: indicate that if it is a script file.
 * fileMode: default true, if set to true, means all commands will store into a script file and execute by /bin/sh.
 * 
 * <P>
 * Version: 3.3 <br>
 * Author: Chen Zhenhua 
 * Date: Apr 10, 2015
 * 
 * </P>
 * 
 **/
import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.jaxb.ActionType;
import com.hp.snap.gr.model.jaxb.LocalShellActionType;
import com.hp.snap.gr.utils.CmdResult;
import com.hp.snap.gr.utils.CmdUtils;
import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;


public class LocalShellActionHandler extends AbstractActionHandler {
    private static Logger logger = LoggerFactory.getLogger(LocalShellActionHandler.class);

    @Override
    public void execute(ActionType action, Map<String, Object> actionPlanInputs,
                        Map<String, Object> actionPlanOutputs) throws ActionException {
        LocalShellActionType localShellAction = (LocalShellActionType) action;
        if (logger.isDebugEnabled()) {
            Utils.printInputParameters(actionPlanInputs);
        }
        String command = localShellAction.getShell();
        try {
            CmdResult result = new CmdResult();
            int rs = CmdUtils.runShellScript(command, result, localShellAction.isFileMode());
            actionPlanOutputs.put(Constants.LOCAL_SHELL_STDOUT, result.getStdout().toString());
            actionPlanOutputs.put(Constants.LOCAL_SHELL_STDERR, result.getStderr().toString());

            if (rs != 0) {
                throw new ActionException("command executed exit code is " + rs);
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new ActionException(ex);
        }
    }

}
